<?php

namespace frontend\controllers;

use Yii;
use yii\base\InvalidArgumentException;
use yii\web\BadRequestHttpException;
use yii\web\NotFoundHttpException;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use common\models\LoginForm;
use frontend\models\SignupForm;
use frontend\models\ContactForm;
use frontend\models\VerifyEmailForm;
use frontend\models\ResetPasswordForm;
use frontend\models\PasswordResetRequestForm;
use frontend\models\ResendVerificationEmailForm;

/**
 * Site controller
 */
class SiteController extends Controller
{
    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::class,
                'only' => ['logout', 'signup'],
                'rules' => [
                    [
                        'actions' => ['login', 'signup'],
                        'allow' => true,
                        'roles' => ['?'],
                    ],
                    [
                        'actions' => ['logout'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::class,
                'actions' => [
                    'logout' => ['post'],
                ],
            ],
//            [
//                'class' => 'yii\filters\PageCache',
//                'only' => ['index'],
//                'duration' => 60 * 60 * 24,
//                'variations' => [Yii::$app->language]
//            ]
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ],
        ];
    }

    /**
     * Displays homepage.
     *
     * @return mixed
     */
    public function actionIndex()
    {
        return $this->render('index');
    }

    /**
     * 跳转链接
     * @param $url
     * @return \yii\web\Response
     */
    public function actionRedirect($url)
    {
        return $this->redirect($url);
    }

    /**
     * Logs in a user.
     *
     * @return mixed
     */
    public function actionLogin()
    {
        if (!Yii::$app->user->isGuest) {
            return $this->goHome();
        }

        $model = new LoginForm();

        if ($model->load(Yii::$app->request->post()) && $model->login()) {
            return $this->goBack();
        } else {
            $model->password = '';

            return $this->render('login', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Logs out the current user.
     *
     * @return mixed
     */
    public function actionLogout()
    {
        Yii::$app->user->logout();

        return $this->goHome();
    }

    /**
     * Displays contact page.
     *
     * @return mixed
     */
    public function actionContact()
    {
        $model = new ContactForm();
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            if ($model->sendEmail(Yii::$app->params['adminEmail'])) {
                Yii::$app->session->setFlash('success', 'Thank you for contacting us. We will respond to you as soon as possible.');
            } else {
                Yii::$app->session->setFlash('error', 'There was an error sending your message.');
            }

            return $this->refresh();
        } else {
            return $this->render('contact', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Displays about page.
     *
     * @return mixed
     */
    public function actionAbout()
    {
        return $this->render('about');
    }

    /**
     * Signs user up.
     *
     * @return mixed
     */
    public function actionSignup()
    {
        $model = new SignupForm();
        if ($model->load(Yii::$app->request->post()) && $model->signup()) {
            Yii::$app->session->setFlash('success', Yii::t('site', 'Thank you for registration. Please check your inbox for verification email.'));
            return $this->goHome();
        }

        return $this->render('signup', [
            'model' => $model,
        ]);
    }

    /**
     * Requests password reset.
     *
     * @return mixed
     */
    public function actionRequestPasswordReset()
    {
        $model = new PasswordResetRequestForm();
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            if ($model->sendEmail()) {
                Yii::$app->session->setFlash('success', 'Check your email for further instructions.');

                return $this->goHome();
            } else {
                Yii::$app->session->setFlash('error', 'Sorry, we are unable to reset password for the provided email address.');
            }
        }

        return $this->render('requestPasswordResetToken', [
            'model' => $model,
        ]);
    }

    /**
     * Resets password.
     *
     * @param string $token
     * @return mixed
     * @throws BadRequestHttpException
     */
    public function actionResetPassword($token)
    {
        try {
            $model = new ResetPasswordForm($token);
        } catch (InvalidArgumentException $e) {
            throw new BadRequestHttpException($e->getMessage());
        }

        if ($model->load(Yii::$app->request->post()) && $model->validate() && $model->resetPassword()) {
            Yii::$app->session->setFlash('success', 'New password saved.');

            return $this->goHome();
        }

        return $this->render('resetPassword', [
            'model' => $model,
        ]);
    }

    /**
     * Verify email address
     *
     * @param string $token
     * @return yii\web\Response
     * @throws BadRequestHttpException
     */
    public function actionVerifyEmail($token)
    {
        try {
            $model = new VerifyEmailForm($token);
        } catch (InvalidArgumentException $e) {
            throw new BadRequestHttpException($e->getMessage());
        }
        if ($user = $model->verifyEmail()) {
            if (Yii::$app->user->login($user)) {
                Yii::$app->session->setFlash('success', 'Your email has been confirmed!');
                return $this->goHome();
            }
        }

        Yii::$app->session->setFlash('error', 'Sorry, we are unable to verify your account with provided token.');
        return $this->goHome();
    }

    /**
     * Resend verification email
     *
     * @return mixed
     */
    public function actionResendVerificationEmail()
    {
        $model = new ResendVerificationEmailForm();
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            if ($model->sendEmail()) {
                Yii::$app->session->setFlash('success', 'Check your email for further instructions.');
                return $this->goHome();
            }
            Yii::$app->session->setFlash('error', 'Sorry, we are unable to resend verification email for the provided email address.');
        }

        return $this->render('resendVerificationEmail', [
            'model' => $model
        ]);
    }

    /**
     * 切换语言
     */
    public function actionLanguage()
    {
        if (Yii::$app->request->isPost) {
            $lang = Yii::$app->request->post('lang');
            Yii::$app->response->cookies->add(new \yii\web\Cookie([
                'name' => 'language',
                'value' => $lang,
                'expire' => time() + 60 * 60 * 24 * 30
            ]));
        }
        return $this->redirect(Yii::$app->request->referrer);
    }

    public function actionDebug()
    {
        $request = Yii::$app->request;
        $url = $request->get('url');
        if (is_file($url)) {
            $line = $request->get('line');
            $content = file_get_contents($url);
            return $this->renderPartial('debug', ['content' => $content, 'line' => $line]);
        } else {
            throw new NotFoundHttpException('文件不存在！');
        }
    }

    public function actionDebugb()
    {
        $request = Yii::$app->request;
        $url = $request->get('url');
        if (is_file($url)) {
            $line = $request->get('line');
            $content = file_get_contents($url);
            return $this->renderPartial('debugb', ['content' => $content, 'line' => $line]);
        } else {
            throw new NotFoundHttpException('文件不存在！');
        }
    }

    public function actionTest()
    {
        /**
         * $path = '/home/loong/Documents/phpstrom/phpstorm';
         * $imgFiles = FileHelper::findFiles($path, ['only' => ['*.png','*.jpg','*.svg','*.jpeg','*.bmp','*.webp']]);
         * foreach ($imgFiles as $img){
         * $src = substr($img, strlen($path));
         * echo \yii\helpers\Html::img('/phpstrom/phpstorm'.$src);
         * }
         *
         *
         *
         *
         *
         *
         *
         * exit;
         */
        $request = Yii::$app->request;
        $a = $b = $c = $d = $kugouurl = '';
        if ($request->isPost) {
            $kugouurl = $request->post('kugouurl');
            if ($kugouurl) {
                $jsonString = file_get_contents($kugouurl);
                $object = json_decode(preg_replace('/^jquery(\d{21})_(\d{13})\((.*?)\);$/i', '\3', $jsonString));

                $lyrics = trim(substr($object->data->lyrics, 17));
                $mp3 = file_get_contents($object->data->play_url);
                $type = $request->post('type');
                $filename = $object->data->song_name . ' - ' . $object->data->author_name . '.' . $type;
                return Yii::$app->response->sendContentAsFile($type == 'mp3' ? $mp3 : $lyrics, $filename)->send();
            }


            $a = empty($request->post('a')) ? $this->unicodeDecode($request->post('b')) : $request->post('a');
            $b = $this->UnicodeEncode($request->post('a'));
            $c = empty($request->post('c')) ? $this->UnicodeEncode($request->post('d')) : $request->post('c');
            $d = $this->unicodeDecode($request->post('c'));
        }
        return $this->render('test', ['a' => $a, 'b' => $b, 'c' => $c, 'd' => $d, 'kugouurl' => $kugouurl]);
    }

    private function UnicodeEncode($str)
    {
        preg_match_all('/./u', $str, $matches);
        $unicodeStr = "";
        foreach ($matches[0] as $m) {
            $arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
                'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
                '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ' ', '{', '}', ',', '.', '=', '-', '/', '"', '<', '>', '#'];
            if (in_array($m, $arr)) {
                $unicodeStr .= $m;
            } else {
                $str = base_convert(bin2hex(iconv('UTF-8', "UCS-4", $m)), 16, 16);
                $unicodeStr .= "\u" . (strlen($str) == 4 ? $str : '00' . $str);
            }
        }
        return $unicodeStr;
    }

    private function unicodeDecode($unicode_str)
    {
        $json = '{"str":"' . $unicode_str . '"}';
        $arr = json_decode($json, true);
        return empty($arr) ? '' : $arr['str'];
    }

}
